﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Cap
{
    internal class EventHostedService : IHostedService
    {
        private readonly BranchOptions _branchOptions;
        private readonly IServiceProvider _serviceProvider;
        private readonly IEnumerable<IEventSourceProvider> _cloudEventProviders;

        public EventHostedService(
            BranchOptions branchOptions,
            IServiceProvider serviceProvider,
            IEnumerable<IEventSourceProvider> cloudEventProviders)
        {
            _branchOptions = branchOptions;
            _serviceProvider = serviceProvider;
            _cloudEventProviders = cloudEventProviders;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            foreach (var sub in _cloudEventProviders)
            {
                sub.Received += SubReceived; ;
                await sub.StartAsync(cancellationToken);
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            foreach (var sub in _cloudEventProviders)
            {
                await sub.StopAsync(cancellationToken);
            }
        }

        private async void SubReceived(object? sender, ICloudEvent e)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                await _branchOptions.Delegate.Invoke(new CloudEventContext(e, scope.ServiceProvider));
            }
        }
    }
}
